package com.accenture.portal.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;


import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.accenture.portal.model.Image;
import com.accenture.portal.model.Scheduling;
import com.accenture.portal.model.User;
import com.accenture.portal.service.ImageService;
import com.accenture.portal.service.SchedulingService;
import com.accenture.portal.service.UserService;

@Controller
public class LoginController {

	
	@Autowired
	@Resource (name="userServiceImpl")
	private UserService us;
	
	@Autowired
	@Resource (name="schedulingServiceImpl")
	private SchedulingService ss;
	
	@Autowired
	private ImageService ims;
	private Image image;
	
	private static Logger login = Logger.getLogger("login");
	
	
	
	/**
	 * 只返回help页面
	 * @author qinhong.wang
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("help.action")
	public ModelAndView help (HttpServletRequest request, HttpServletResponse response, Model model) {
		return new ModelAndView ("login/help");
	}
	
	/**
	 * 登录界面，只返回登录页
	 * @author qinhong.wang
	 * @param request
	 * @param response
	 * @return login.jsp
	 */
	@RequestMapping("loginView.action")
	public ModelAndView loginView (HttpServletRequest request, HttpServletResponse response) {
		return new ModelAndView ("login/login");
	}
	
	/**
	 * 登录界面，只返回登录页
	 * @author qinhong.wang
	 * @param request
	 * @param response
	 * @return login.jsp
	 */
	@RequestMapping("index.action")
	public ModelAndView index (HttpServletRequest request, HttpServletResponse response) {
		return new ModelAndView ("login/index");
	}
	
	/**
	 * 绘制验证码
	 * @author cuiying.cao
	 * @param request
	 * @param response
	 * @param session
	 */
	@RequestMapping("authCode.action")
	public void getAuthCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
		int width = 63;
		int height = 37;
		Random random = new Random();
		//设置response 头信息
		//禁止缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		//生成缓冲区image类
		BufferedImage image = new BufferedImage(width, height, 1);
		//产生image类的Graphics用于绘制操作
		Graphics g = image.getGraphics();
		//Graphics类的样式
		g.setColor(this.getRandColor(200,250));
		g.setFont(new Font("Times New Roman", 0,28));
		g.fillRect(0, 0, width, height);
		//绘制干扰线
		
		for(int i = 0;i < 40;i++) {
			g.setColor(this.getRandColor(130,200));
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int x1 = random.nextInt(12);
			int y1 = random.nextInt(12);
			g.drawLine(x, y, x + x1, y + y1);
		}
		
		//绘制字符
		String strCode = "";
		for(int i =0;i < 4;i++) {
			String rand = String.valueOf(random.nextInt(10));
			strCode = strCode + rand;
			g.setColor(new Color(20 + random.nextInt(110),20 + random.nextInt(110),20 + random.nextInt(110)));
			g.drawString(rand, 13*i+6, 28);
		}
		
		//将字符保存到session中的前端的验证(前台未接收到strCode)
		session.setAttribute("strCode", strCode);
		
		g.dispose();
		
		ImageIO.write(image, "JPEG", response.getOutputStream());
		response.getOutputStream().flush();
		
	}
	
	//创建生成颜色的方法
		Color getRandColor(int fc, int bc) {
			Random random = new Random();
			if(fc > 255)
				fc = 255;
			if(bc > 255)
				bc = 255;
			int r = fc + random.nextInt(bc - fc);
			int g = fc + random.nextInt(bc - fc);
			int b = fc + random.nextInt(bc - fc);
			return new Color(r,g,b);
			
		}	
		
		/**
		 * 验证码的验证
		 * @author cuiying.cao
		 * @param strCode
		 * @param checkcode
		 */
		public int verifyAuthCode(String strCode, String checkcode) {
			if(checkcode == null||checkcode.equals("")) {
				return 0;//空
			} else if(!checkcode.equals(strCode)) {
				return -1;//错误
			} else {
				return 1;//正确
			}
		}
		
		/**
		 * 用户验证
		 * @author cuiying.cao
		 * @param user_id
		 * @param user_password
		 */
		public int verifyUser(Integer user_id, String user_password) {
			User loginUser = us.login(user_id);
			if(loginUser == null) {//用户是否存在
				return -1;
			}  else if (user_password == ""){//密码必填
				return 0;
			} else if(!loginUser.getUser_password().equals(user_password)) {
				return 1;//密码不对
			} else {
				return 2;//匹配
			}
			 
		}
	
	/**
	 * 登录验证
	 * @author qinhong.wang
	 * @author cuiying.cao
	 * @param request
	 * @param response
	 * @param model
	 * @param user_id 
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping("login.action")
	public String login (HttpServletRequest request, HttpServletResponse response,
			HttpSession session, Model model, Integer user_id) throws ParseException {
		
		//获取页面输入的验证码
		String checkcode = (String) request.getParameter("checkCode");
		String strCode = (String) session.getAttribute("strCode");
		String user_password = (String) request.getParameter("user_password");
		
		//验证码校验
		int authCodeFlag = verifyAuthCode(strCode, checkcode);
		if(authCodeFlag == 0) {
			model.addAttribute("nullCheckCodeMsg", "checkCode can not be empty.");
			return "login/login";
		} else if(authCodeFlag == -1) {
			model.addAttribute("failCheckCodeMsg", "Incorrect checkCode. Please try again.");
			return "login/login";
		} else {
			//验证是否有用户和密码
			int userFlag = verifyUser(user_id, user_password);
			if(userFlag == -1) {
				model.addAttribute("noThisIdMsg", "The userID not exist.");
				return "login/login";
			} else {
				User logUser = us.searchById(user_id);
				//账号密码是否过期
				Date idCreatTime = logUser.getIdCreatTime();//获取创建 时间
				Date pwCreatTime = logUser.getPwCreatTime();
				Date nowTime = new Date();
				
				long nt = nowTime.getTime();
				long it = idCreatTime.getTime();
				long pt = pwCreatTime.getTime();
				
				long idtest = Math.abs(nt - it);
				long pwtest = Math.abs(pt - nt);
				
				 long idt = (idtest/1000/60/60/24);
				 long pwt = (pwtest/1000/60/60/24);
				
				if(idt > 30) {//账号有效期30天
					model.addAttribute("idOutOfTimeMsg", "Your ID has out of time.");
					return "login/login";
				}else if(pwt > 10) {//密码有效期10天
					model.addAttribute("pwOutOfTimeMsg", "Your password has out of time.");
					return "login/login";
				} else {
					//判断登录失败次数
					
					int loginErrorTimes = us.loginErrorTimes(user_id);
					if(loginErrorTimes >= 3) {//已连续失败3次，账号锁定
						model.addAttribute("idLockMsg", "Your ID has been locked,please wait for the administrator to unlock.");
						return "login/login";
					} else {
						if(userFlag == 0) {//密码不为空
							model.addAttribute("nullPasswordMsg", "Password can not be empty.");
							return "login/login";
						} else if(userFlag == 1) {//密码错误
							model.addAttribute("failPasswordMsg", "Incorrect password.");
							loginErrorTimes++;
							logUser.setLoginErrorTimes(loginErrorTimes);
							us.update(logUser);

							if(loginErrorTimes == 1) {
								model.addAttribute("pwWrongOneMsg", "You have only two opportunities.");
							} else if(loginErrorTimes == 2) {
								model.addAttribute("pwWrongTwoMsg", "You have only one opportunity.");
							} else if(loginErrorTimes == 3) {
								model.addAttribute("idLockMsg", "Your ID has been locked,please wait for the administrator to unlock.");
							}

							return "login/login";
						}else if(logUser.getUser_flag() == 0) {
							model.addAttribute("activationMsg", "Your ID has not been activation.");
							return "login/login";
						}  
						else {
							User loggedUser = us.searchById(user_id);
							request.getSession().setAttribute("user", loggedUser);
							
							List<Scheduling> list = ss.selectSchedulingByUserId(loggedUser.getUser_id());
							
							if(list.size() >= 1) {
								List<Scheduling> subList = list.subList(0, 1);
								Scheduling scheduling = subList.get(0);
								request.getSession().setAttribute("scheduling", scheduling);
							} else {
								/*添加新用户后未设置scheduling时，将mycvResume设为系统当前时间*/
								Scheduling scheduling = new Scheduling();
								Date now = new Date();
								SimpleDateFormat formatter = new SimpleDateFormat("MMM dd,yyyy",Locale.ENGLISH);
								String mycvResume = formatter.format(now);
								Date date =null;
								try{
									date=formatter.parse(mycvResume);
								}catch(ParseException  e){
									e.printStackTrace();
								}
								scheduling.setMycvResume(date);			
								request.getSession().setAttribute("scheduling", scheduling);
							}
							
							image = new Image();
							Image newimage = ims.findnewimg(image.getImgid());
							request.getSession().setAttribute("image", newimage);
							
							List<Image> imagelist = ims.findEff();
							int imgsize = imagelist.size();
							if (imgsize >= 5)
							{
								int first = imgsize-5;
								int last = imgsize-1;
								List<Image> imglist = imagelist.subList(first, last);
								request.getSession().setAttribute("imageList", imglist);
							}
							else
							{
								int last = imgsize-1;
								if(last==-1){
									last=0;
								}
								List<Image> imgslist = imagelist.subList(0, last);
								request.getSession().setAttribute("imageList", imgslist);
							}
							
							//PropertyConfigurator.configure("C:/Asset2.0/workspace1/Accenture_Portal2.0/src/log4j.properties");//使用自定义的log4j appender 
							
							String IP = request.getRemoteAddr();
							User user=(User)request.getSession().getAttribute("user");
							String userName =user.getUser_name();
							
							//LogManagerUtil.recordLoginLog("127.0.0.1", "Alice", "success", "login success!");
							
							LogManagerUtil.recordLoginLog(IP, userName, "success", "success !");
							login.debug("test MDC");
							
							return "login/index";
						}
					}
					
				}
				
				
			}
			
		}
		
	}
	
	
}
